package com.wechatFriendExportTool.utils;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ExcelDesktopUtils {
    
    /**
     * 保存SXSSFWorkbook到桌面的完整方法
     */
    public static File saveToDesktop(SXSSFWorkbook workbook, String desiredFileName) {
        return saveToDesktop(workbook, desiredFileName, true);
    }
    
    /**
     * 保存SXSSFWorkbook到桌面
     * @param workbook SXSSFWorkbook实例
     * @param desiredFileName 期望的文件名
     * @param autoDispose 是否自动dispose workbook
     * @return 保存的File对象，如果失败返回null
     */
    public static File saveToDesktop(SXSSFWorkbook workbook, String desiredFileName, boolean autoDispose) {
        // 验证参数
        if (workbook == null) {
            throw new IllegalArgumentException("Workbook不能为null");
        }
        
        if (desiredFileName == null || desiredFileName.trim().isEmpty()) {
            desiredFileName = "excel_file_" + System.currentTimeMillis();
        }
        
        // 处理文件名
        String finalFileName = processFileName(desiredFileName);
        
        // 获取桌面文件
        File desktopFile = getDesktopFile(finalFileName);
        
        // 保存文件
        boolean success = writeWorkbookToFile(workbook, desktopFile);
        
        if (success) {
            System.out.println("✅ Excel文件已成功保存到桌面: " + desktopFile.getName());
            System.out.println("📍 完整路径: " + desktopFile.getAbsolutePath());
            
            // 如果自动dispose，则清理资源
            if (autoDispose) {
                try {
                    workbook.dispose();
                } catch (Exception e) {
                    System.err.println("警告: 清理workbook资源时出错: " + e.getMessage());
                }
            }
            
            return desktopFile;
        } else {
            System.err.println("❌ 保存文件失败");
            return null;
        }
    }
    
    /**
     * 处理文件名
     */
    private static String processFileName(String desiredFileName) {
        String fileName = desiredFileName.trim();
        
        // 确保有.xlsx扩展名
        if (!fileName.toLowerCase().endsWith(".xlsx")) {
            fileName += ".xlsx";
        }
        
        // 处理无效字符
        fileName = fileName.replaceAll("[\\\\/:*?\"<>|]", "_");
        
        return fileName;
    }
    
    /**
     * 获取桌面文件，处理文件名冲突
     */
    private static File getDesktopFile(String fileName) {
        File desktopDir = getDesktopDirectory();
        File targetFile = new File(desktopDir, fileName);
        
        // 处理文件名冲突
        if (targetFile.exists()) {
            String baseName = fileName.replaceFirst("\\.xlsx$", "");
            String extension = ".xlsx";
            int counter = 1;
            
            do {
                String newFileName = baseName + "(" + counter + ")" + extension;
                targetFile = new File(desktopDir, newFileName);
                counter++;
            } while (targetFile.exists());
        }
        
        return targetFile;
    }
    
    /**
     * 获取桌面目录
     */
    private static File getDesktopDirectory() {
        String userHome = System.getProperty("user.home");
        File desktop = new File(userHome, "Desktop");
        
        // 如果默认桌面目录不存在，尝试其他语言
        if (!desktop.exists() || !desktop.isDirectory()) {
            String[] possibleNames = {
                "Desktop", "桌面", "Escritorio", "Bureau", 
                "Schreibtisch", "Рабочий стол", "桌面"
            };
            
            for (String name : possibleNames) {
                File possibleDesktop = new File(userHome, name);
                if (possibleDesktop.exists() && possibleDesktop.isDirectory()) {
                    return possibleDesktop;
                }
            }
            
            // 如果都找不到，使用用户主目录
            return new File(userHome);
        }
        
        return desktop;
    }
    
    /**
     * 将workbook写入文件
     */
    private static boolean writeWorkbookToFile(SXSSFWorkbook workbook, File file) {
        // 确保父目录存在
        File parentDir = file.getParentFile();
        if (!parentDir.exists()) {
            boolean dirsCreated = parentDir.mkdirs();
            if (!dirsCreated) {
                System.err.println("无法创建目录: " + parentDir.getAbsolutePath());
                return false;
            }
        }
        
        try (FileOutputStream fos = new FileOutputStream(file)) {
            workbook.write(fos);
            return true;
        } catch (IOException e) {
            System.err.println("写入文件时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 生成带时间戳的报表文件
     */
    public static File saveReportWithTimestamp(SXSSFWorkbook workbook, String reportType) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timestamp = sdf.format(new Date());
        String fileName = reportType + "_" + timestamp + ".xlsx";
        
        return saveToDesktop(workbook, fileName);
    }
    
    /**
     * 获取桌面路径信息（用于调试）
     */
    public static void printDesktopInfo() {
        System.out.println("=== 桌面路径信息 ===");
        System.out.println("用户主目录: " + System.getProperty("user.home"));
        System.out.println("操作系统: " + System.getProperty("os.name"));
        System.out.println("桌面目录: " + getDesktopDirectory().getAbsolutePath());
        
        File desktop = getDesktopDirectory();
        System.out.println("桌面存在: " + desktop.exists());
        System.out.println("桌面可写: " + desktop.canWrite());
        
        if (desktop.exists()) {
            String[] files = desktop.list();
            System.out.println("桌面文件数量: " + (files != null ? files.length : 0));
        }
    }
    
    public static void main(String[] args) {
        // 显示桌面信息
        printDesktopInfo();
        
        // 创建示例workbook并保存
        try {
            SXSSFWorkbook workbook = new SXSSFWorkbook(100);
            workbook.createSheet("测试数据").createRow(0).createCell(0).setCellValue("测试内容");
            
            // 保存示例
            File savedFile = saveToDesktop(workbook, "测试Excel文件");
            if (savedFile != null) {
                System.out.println("文件大小: " + savedFile.length() + " 字节");
            }
            
            // 保存带时间戳的报表
            File reportFile = saveReportWithTimestamp(workbook, "销售报表");
            if (reportFile != null) {
                System.out.println("报表文件: " + reportFile.getName());
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}